import { Component, OnInit, OnDestroy } from '@angular/core';
import { OtherWarehousing, OtherWarehousingFilter, OtherWarehousingService, SelectOption } from './other-warehousing.service';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { CoreModule } from '@abp/ng.core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { OtherWarehousingCreateComponent } from './other-warehousing-create.component';
import { OtherWarehousingViewComponent } from './other-warehousing-view.component';
import { ToasterService } from '@abp/ng.theme.shared';
import { finalize, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-other-warehousing',
  template: `
    <div class="page-transition">
      <!-- 统计卡片 -->
      <div class="row mb-4">
        <div class="col-md-3">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="fas fa-box"></i>
            </div>
            <div class="stat-value">{{totalCount}}</div>
            <div class="stat-label">总入库单数</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="fas fa-clock"></i>
            </div>
            <div class="stat-value">{{getPendingCount()}}</div>
            <div class="stat-label">待处理入库单</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-value">{{getCompletedCount()}}</div>
            <div class="stat-label">已完成入库单</div>
          </div>
        </div>
        <div class="col-md-3">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="fas fa-truck"></i>
            </div>
            <div class="stat-value">{{getInTransitCount()}}</div>
            <div class="stat-label">在途入库单</div>
          </div>
        </div>
      </div>

      <div class="modern-card fade-in">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h4><i class="fas fa-warehouse me-2"></i>其它入库管理</h4>
          <small class="text-muted">默认显示前后7天数据</small>
        </div>
        <div class="card-body">
          <!-- 搜索区域 -->
          <div class="search-area">
            <div class="search-title">
              <i class="fas fa-search"></i>
              <span>搜索条件</span>
            </div>
            <form (ngSubmit)="search()" class="modern-form">
              <div class="row">
                <div class="col-md-3">
                  <div class="form-group">
                    <label>通知单号</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.purchaseOrderNo" name="purchaseOrderNo" placeholder="请输入通知单号">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>货主编码</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.ownerCode" name="ownerCode" placeholder="请输入货主编码">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>客户订单号</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.customerOrderNo" name="customerOrderNo" placeholder="请输入客户订单号">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>车号</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.carNo" name="carNo" placeholder="请输入车号">
                  </div>
                </div>
              </div>
              <div class="row mt-2">
                <div class="col-md-3">
                  <div class="form-group">
                    <label>司机</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.driverName" name="driverName" placeholder="请输入司机姓名">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>司机电话</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.driverPhone" name="driverPhone" placeholder="请输入司机电话">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>预计到货时间(起)</label>
                    <input type="date" class="form-control" [(ngModel)]="filter.expectedArrivalDateFrom" name="expectedArrivalDateFrom">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>预计到货时间(止)</label>
                    <input type="date" class="form-control" [(ngModel)]="filter.expectedArrivalDateTo" name="expectedArrivalDateTo">
                  </div>
                </div>
              </div>
              <div class="row mt-2">
                <div class="col-md-3">
                  <div class="form-group">
                    <label>订单类型</label>
                    <select class="form-control" [(ngModel)]="filter.orderType" name="orderType">
                      <option [ngValue]="undefined">全部</option>
                      <option *ngFor="let type of orderTypes" [ngValue]="type.value">{{type.name}}</option>
                    </select>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>月台</label>
                    <select class="form-control" [(ngModel)]="filter.platform" name="platform">
                      <option [ngValue]="undefined">全部</option>
                      <option *ngFor="let p of platforms" [ngValue]="p.value">{{p.name}}</option>
                    </select>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>单据状态</label>
                    <select class="form-control" [(ngModel)]="filter.status" name="status">
                      <option [ngValue]="undefined">全部</option>
                      <option value="计划中">计划中</option>
                      <option value="已完成">已完成</option>
                    </select>
                  </div>
                </div>
              </div>
            </form>
          </div>

          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="left-actions">
              <button type="button" class="modern-btn btn-primary" (click)="openCreateDialog()">
                <i class="fas fa-plus"></i>
                <span>录入</span>
              </button>
              <button type="button" class="modern-btn btn-success" (click)="openViewDialog()" [disabled]="!selected.length">
                <i class="fas fa-info-circle"></i>
                <span>查看</span>
              </button>
            </div>
            <div class="right-actions">
              <button type="submit" class="modern-btn btn-info" (click)="search()">
                <i class="fas fa-search"></i>
                <span>查询</span>
              </button>
              <button type="button" class="modern-btn btn-secondary" (click)="reset()">
                <i class="fas fa-sync"></i>
                <span>重置</span>
              </button>
            </div>
          </div>
          
          <!-- 数据表格 -->
          <div class="table-responsive mt-3">
            <ngx-datatable
              class="material modern-table"
              [rows]="items"
              [columnMode]="'force'"
              [headerHeight]="50"
              [footerHeight]="50"
              [rowHeight]="'auto'"
              [count]="totalCount"
              [externalPaging]="true"
              [externalSorting]="true"
              [loadingIndicator]="isLoading"
              [limit]="pageSize"
              [offset]="pageNumber"
              (page)="onPage($event)"
              (sort)="onSort($event)"
              [selectionType]="'checkbox'"
              (select)="onSelect($event)"
              [selected]="selected"
            >
              <ngx-datatable-column
                [width]="50"
                [sortable]="false"
                [canAutoResize]="false"
                [draggable]="false"
                [resizeable]="false"
                [headerCheckboxable]="true"
                [checkboxable]="true"
              >
              </ngx-datatable-column>
              <ngx-datatable-column name="创建人名称" prop="creatorName">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-user me-1"></i>admin
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="创建日期" prop="creationTime">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="far fa-calendar-alt me-1"></i>{{ value | date: 'yyyy-MM-dd' }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="通知单号" prop="orderNo">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-file-alt me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="货主编码" prop="ownerCode">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-building me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="预计到货时间" prop="estimatedArrivalTime">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="far fa-clock me-1"></i>{{ value | date: 'yyyy-MM-dd HH:mm:ss' }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="客户订单号" prop="customerOrderNo">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-shopping-cart me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="车号" prop="carNo">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-truck me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="司机" prop="driverName">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-id-card me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="司机电话" prop="driverPhone">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-phone me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="订单类型" prop="orderType">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-tags me-1"></i>{{ getOrderTypeName(value) }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="月台" prop="platform">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-warehouse me-1"></i>{{ getPlatformName(value) }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="备注" prop="remark">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-comment-alt me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="单据状态" prop="status">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <span class="status-badge" [ngClass]="{
                    'status-pending': value === '计划中',
                    'status-completed': value === '已完成',
                    'status-processing': value === '处理中'
                  }">
                    <i class="fas" [ngClass]="{
                      'fa-clock': value === '计划中',
                      'fa-check-circle': value === '已完成',
                      'fa-spinner fa-spin': value === '处理中'
                    }"></i>
                    {{ value }}
                  </span>
                </ng-template>
              </ngx-datatable-column>
            </ngx-datatable>
          </div>

          <!-- 加载动画 -->
          <div *ngIf="isLoading" class="text-center mt-3">
            <div class="loading-spinner mx-auto"></div>
          </div>
        </div>
      </div>
    </div>
  `,
  standalone: true,
  imports: [CommonModule, FormsModule, NgxDatatableModule, ThemeSharedModule, CoreModule],
  styleUrls: ['../shared/purchase.styles.scss']
})
export class OtherWarehousingComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  items: OtherWarehousing[] = [];
  selected: OtherWarehousing[] = [];
  totalCount = 0;
  pageSize = 10;
  pageNumber = 0;
  sorting = '';
  isLoading = false;

  orderTypes: SelectOption[] = [];
  platforms: SelectOption[] = [];

  filter: OtherWarehousingFilter = {
    maxResultCount: this.pageSize,
    skipCount: 0,
    sorting: ''
  };

  constructor(
    private service: OtherWarehousingService,
    private modalService: NgbModal,
    private toaster: ToasterService
  ) {}

  ngOnInit(): void {
    this.loadDropdowns();
    this.search();

    // 订阅刷新事件
    this.service.refresh$
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {
        this.search();
      });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  loadDropdowns() {
    // 加载订单类型
    this.service.getOrderTypes().subscribe({
      next: (response) => {
        this.orderTypes = response.items || [];
      },
      error: (error) => {
        console.error('加载订单类型失败:', error);
        this.toaster.error('加载订单类型失败');
      }
    });

    // 加载月台
    this.service.getPlatforms().subscribe({
      next: (response) => {
        this.platforms = response.items || [];
      },
      error: (error) => {
        console.error('加载月台失败:', error);
        this.toaster.error('加载月台失败');
      }
    });
  }

  search(): void {
    this.isLoading = true;
    const params = {
      ...this.filter,
      maxResultCount: this.pageSize,
      skipCount: this.pageNumber * this.pageSize,
      sorting: this.sorting,
    };

    console.log('Search params:', params);

    this.service.getListByConditions(params).subscribe({
      next: (result) => {
        console.log('Search result:', result);
        this.items = result.items;
        this.totalCount = result.totalCount;
        this.isLoading = false;
      },
      error: (error) => {
        console.error('查询失败:', error);
        this.toaster.error('查询失败，请重试');
        this.isLoading = false;
      }
    });
  }

  reset(): void {
    this.pageNumber = 0;
    this.filter = {
      maxResultCount: this.pageSize,
      skipCount: 0,
      sorting: '',
      purchaseOrderNo: undefined,
      ownerCode: undefined,
      orderType: undefined,
      customerOrderNo: undefined,
      carNo: undefined,
      driverName: undefined,
      driverPhone: undefined,
      expectedArrivalDateFrom: undefined,
      expectedArrivalDateTo: undefined,
      status: undefined,
      platform: undefined
    };
    this.search();
  }

  onPage(event: any): void {
    console.log('Page event:', event);
    if (this.pageNumber !== event.offset || this.pageSize !== event.limit) {
      this.pageNumber = event.offset;
      this.pageSize = event.limit;
      this.filter.maxResultCount = this.pageSize;
      this.filter.skipCount = this.pageNumber * this.pageSize;
      this.search();
    }
  }

  onSort(event: any): void {
    console.log('Sort event:', event);
    const sortField = event.sorts[0];
    this.sorting = sortField ? `${sortField.prop} ${sortField.dir}` : '';
    this.search();
  }

  onSelect(event: any): void {
    this.selected = event.selected;
  }

  openCreateDialog() {
    const modalRef = this.modalService.open(OtherWarehousingCreateComponent, { 
      size: 'lg',
      backdrop: 'static'
    });
    
    modalRef.result.then(
      (result) => {
        if (result && result.success) {
          this.search(); // 刷新列表数据
        }
      },
      () => {} // 用户取消关闭
    );
  }

  openViewDialog() {
    if (this.selected.length !== 1) {
      this.toaster.error('请选择一条记录查看');
      return;
    }

    const modalRef = this.modalService.open(OtherWarehousingViewComponent, { size: 'xl' });
    modalRef.componentInstance.id = this.selected[0].id;
  }

  getOrderTypeName(value: any): string {
    const type = this.orderTypes.find(t => t.value === value);
    return type ? type.name : value?.toString() || '';
  }

  getPlatformName(value: any): string {
    const platform = this.platforms.find(p => p.value === value);
    return platform ? platform.name : value?.toString() || '';
  }

  getPendingCount(): number {
    return this.items.filter(item => item.status === '计划中').length;
  }

  getCompletedCount(): number {
    return this.items.filter(item => item.status === '已完成').length;
  }

  getInTransitCount(): number {
    return this.items.filter(item => item.status === '处理中').length;
  }
} 